<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose" destroyOnClose>
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ sm: 4, lg: 6 }">
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="配送司机" name="driver_id">
              <Select name="Driver" v-model:value="form.driver_id" placeholder="配送司机" @change="onDriverChange" allowClear />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="协送员" name="escort_driver_id">
              <Select name="Driver" v-model:value="form.escort_driver_id" placeholder="协送员" @change="onEscortDriverChange" allowClear />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </a-form>

    <a-card title="单据信息">
      <a-table :columns="orderColumn" :loading="checkOrderTableLoading" :data-source="checkOrderListComputed" size="small" :scroll="{ x: 'max-content', y: 369 }" :pagination="false" row-key="id">
        <template #bodyCell="{ record, text, column }">
          <template v-if="column.dataIndex === 'no'">
            <template v-if="record?.order_type === 1">
              <a-badge count="销" color="#f50" />
            </template>
            <template v-if="record?.order_type === 2">
              <a-badge count="退" color="#87d068" />
            </template>
            <template v-if="record?.order_type === 3">
              <a-badge count="换" color="#2db7f5" />
            </template>
            <template v-if="record?.order_type === 4">
              <a-badge count="订" color="#108ee9" />
            </template>
            <template v-if="record?.order_type === 5">
              <a-badge count="退" color="#199ee9" />
            </template>
            <template v-if="text">
              <CopyText :text="text">
                <span>{{ text }}</span>
              </CopyText>
            </template>
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ record?.warehouse?.name }}<span v-if="record.warehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.warehouse?.attribute_type) }})</span></span
            >
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell>
                <a-input readonly placeholder="请选择订单" size="small" style="width: 180px" @click="changeOrderModal(true)">
                  <template #suffix>
                    <a-button @click="changeOrderModal(true)" type="link">选择订单</a-button>
                  </template>
                </a-input>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </a-card>
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" style="margin-right: 8px" @click="onSubmit" :disabled="!isWarehouse">保存</a-button>
        <template v-if="form?.id">
          <a-button type="primary" style="margin-right: 8px" v-if="form?.id" @click="toMap('/sort')">规划</a-button>
          <a-button type="primary" @click="toMap('')">地图调度</a-button>
        </template>
      </div>
    </template>
    <a-modal v-model:open="showOrderModal" width="50vw" title="选择订单" @ok="confirmAddCheckOrder">
      <a-form ref="orderQueryFormRef" :model="orderQueryFilter" style="width: 100%; padding: 8px 0" size="small">
        <a-row :gutter="[8, 10]">
          <a-col :span="8">
            <a-form-item label="单据日期" class="smart-margin-bottom0" name="create_time">
              <a-range-picker v-model:value="orderQueryFilter.create_time" valueFormat="YYYY-MM-DD" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="仓库" class="smart-margin-bottom0" name="warehouse_id">
              <Select name="Warehouse" v-model:value="orderQueryFilter.warehouse_id" placeholder="仓库" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-button-group>
              <a-button type="primary" html-type="submit" @click="onSearchOrderList">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button @click="resetOrderQuery">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
              <SearchFormCollapse v-model="expand" />
            </a-button-group>
          </a-col>
          <template v-if="expand">
            <a-col :span="8">
              <a-form-item label="业务员" class="smart-margin-bottom0" name="salesman_id">
                <Select name="Salesman" v-model:value="orderQueryFilter.salesman_id" placeholder="业务员" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="门店" class="smart-margin-bottom0" name="store_id">
                <Select name="Store" v-model:value="orderQueryFilter.store_id" placeholder="门店" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="销售单号" class="smart-margin-bottom0" name="no">
                <a-input v-model:value.trim="orderQueryFilter.no" placeholder="销售单号" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="订单类型" class="smart-margin-bottom0" name="order_type">
                <EnumSelect enum-name="ORDER_STATRS_ENUM" v-model:value="orderQueryFilter.order_type" placeholder="单据类型" />
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>
      <a-table :columns="orderColumn" :loading="orderTableLoading" :data-source="orderList" size="small" :scroll="{ x: 'max-content', y: 369 }" :pagination="false" :row-selection="getOrderSelection()" row-key="id">
        <template #bodyCell="{ record, text, column }">
          <template v-if="column.dataIndex === 'no'">
            <a-badge :count="badgeText(record?.order_type)" :color="badgeColor(record?.order_type)" />
            <span>{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ record?.warehouse?.name }}<span v-if="record.warehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.warehouse?.attribute_type) }})</span></span
            >
          </template>
        </template>
      </a-table>
      <div class="smart-query-table-page query-table-page smart-margin-bottom10 smart-margin-right10">
        <a-pagination size="small" showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="orderPagination.limit" v-model:current="orderPagination.page" v-model:pageSize="orderPagination.limit" :total="orderPagination.total" :show-total="orderTotalComputed" @change="onSearchOrderList" @showSizeChange="onSearchOrderList" />
      </div>
    </a-modal>
  </a-drawer>
</template>
<script setup lang="ts">
import _ from 'lodash'
import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
import { message } from 'ant-design-vue'
import Select from '@/components/business/select/index.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import { useEnums } from '@/hooks/plugins/useEnums'
import { salesApi } from '@/api/business/sale/sales-api'
import { taskApi } from '@/api/business/logistics/delivery-api'
import { warehouseApi } from '@/api/business/storage/warehouse-api'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
const loadingStore = useLoadingStore()
const expand = ref(false)
const { getDescByValue } = useEnums()
dayjs.extend(isBetween)
let checkOrderSource = [] // 记录编辑时已分配的订单ID
const removedOrders = ref<any[]>([]) // 删除的订单

const badgeText = (val) => {
  switch (val) {
    case 1:
      return '销'
    case 2:
      return '退'
    case 3:
      return '换'
    case 4:
      return '订'
    case 5:
      return '退'
    default:
      return ''
  }
}

const badgeColor = (val) => {
  switch (val) {
    case 1:
      return '#f50'
    case 2:
      return '#87d068'
    case 3:
      return '#2db7f5'
    case 4:
      return '#108ee9'
    case 5:
      return '#199ee9'
    default:
      return ''
  }
}

// 检测司机是否拥有移动仓
const isWarehouse = ref(false)

// emit
const emit = defineEmits(['reload-list'])
// 表单数据
const formRef = ref()
const formDefault = {
  order_ids: '',
  // 配送司机
  driver_id: undefined,
  // 协送员
  escort_driver_id: undefined,
  status: 1
}
const form: any = ref(_.cloneDeep(formDefault))
const rules = {
  driver_id: [{ required: true, message: '请选择配送司机', trigger: 'blur' }]
}

async function onSubmit() {
  if (checkOrderList.value.length === 0) {
    message.error('请选择配送单')
    return
  }
  let order_ids: any = []
  if (unref(form)?.id) {
    const ids = new Set([checkOrderSource.map((id) => id), checkOrderList.value.map(({ id }) => id)].flat(1)) // 用于提交时的订单ID列表
    order_ids = Array.from(ids).map((id) => {
      return {
        id,
        is_delete: checkOrderList.value.findIndex((item) => item.id === id) === -1 ? 1 : 0 // 如果订单不在已分配列表中，则标记为删除
      }
    })
  } else {
    order_ids = checkOrderList.value.map(({ id }) => ({ id }))
  }
  const data: any = {
    ...unref(form),
    order_ids: JSON.stringify(order_ids),
    sort: JSON.stringify(checkOrderList.value.map(({ id: order_id }, sort) => ({ order_id, sort })))
  }
  data.escort_driver_id = data?.escort_driver_id ?? ''
  formRef.value.validate().then(async () => {
    loadingStore.show()
    try {
      const res: any = await taskApi[unref(form)?.id ? 'editLoad' : 'addLoad'](data)
      message.success(res.msg)
      onClose()
      emit('reload-list')
    } catch (error: any) {
      message.error(error.msg)
      errorSentry.captureError(error)
    } finally {
      loadingStore.hide()
    }
  })
}

// 是否展示抽屉
const visible = ref(false)
async function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData?.id && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    form.value.escort_driver_id = rowData.escort_driver_id == 0 ? undefined : rowData.escort_driver_id
    onDriverChange(form.value.driver_id)
    await getCheckOrderList()
  }
  getOrderList()
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
defineExpose({
  showDrawer
})

function onClose() {
  visible.value = false
  checkOrderList.value = []
  orderSelectedKeys.value = []
  orderSelectedRows.value = []
}

// 司机
async function onDriverChange(value) {
  if (!value) return
  if (value === form.value.escort_driver_id) form.value.escort_driver_id = undefined
  const res = await warehouseApi.checkDriver({ driver_id: value })
  isWarehouse.value = res.data.isWarehouse
  if (!res.data.isWarehouse) {
    message.error('该司机没有创建移动仓，请先创建移动仓')
  }
}
// 协送员
function onEscortDriverChange(value) {
  if (value === form.value.driver_id) form.value.driver_id = undefined
}

// ---------------------------- 已分配的订单 -------------------------
const checkOrderList = ref<any[]>([])
const checkOrderListComputed = computed(() => [...checkOrderList.value, {}])
const checkOrderTableLoading = ref(false)
async function getCheckOrderList() {
  function handleData(row) {
    return {
      ...row,
      detail_sum: _(row.detail)
        .map(({ total_price }) => Number(total_price))
        .sum()
        .toFixed(2),
      is_load: true
    }
  }
  try {
    checkOrderTableLoading.value = true
    const res: any = await taskApi.detailLoad({ id: form.value.id })
    checkOrderList.value = res.data.data.map(handleData)
    checkOrderSource = res.data.data.map(({ id }) => id)
  } catch (error: any) {
    message.error(error.msg)
  } finally {
    checkOrderTableLoading.value = false
  }
}

// ---------------------------- 未分配的订单 -------------------------
// 查询部分
const orderQueryFormRef = ref()
const orderPagination = ref({
  page: 1,
  limit: 10,
  total: 0
})
const orderQueryFilter = ref({
  no: '',
  create_time: [],
  warehouse_id: undefined,
  salesman_id: undefined,
  store_id: undefined,
  type: 1,
  is_delivery: 1,
  is_self: 1,
  status: '2,6',
  order_type: undefined
})
const orderQueryOp = {
  no: QUERY_FORM_OP['模糊查询'],
  create_time: QUERY_FORM_OP['范围查询'],
  warehouse_id: QUERY_FORM_OP['全等查询'],
  salesman_id: QUERY_FORM_OP['全等查询'],
  store_id: QUERY_FORM_OP['全等查询'],
  type: QUERY_FORM_OP['全等查询'],
  is_delivery: QUERY_FORM_OP['不等查询'],
  is_self: QUERY_FORM_OP['不等查询'],
  status: QUERY_FORM_OP['IN查询']
}
function onSearchOrderList() {
  getOrderList()
}
function resetOrderQuery() {
  orderQueryFormRef.value.resetFields()
  getOrderList()
}

// 列表
const orderList = ref<any[]>([])
const orderColumn = [
  {
    title: '仓库',
    dataIndex: 'warehouse_name'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  },
  {
    title: '片区',
    dataIndex: ['store', 'region', 'name']
  },
  {
    title: '单据编号',
    dataIndex: 'no',
    width: 260
  },
  {
    title: '订单数量',
    dataIndex: 'order_number'
  },
  {
    title: '订单金额',
    dataIndex: 'discounted_amount'
  },
  {
    title: '门店',
    dataIndex: ['store', 'store_name']
  },
  {
    title: '业务员',
    dataIndex: ['salesman', 'rename']
  },
  {
    title: '经销商',
    dataIndex: ['dealer', 'name']
  },
  {
    title: '单据日期',
    dataIndex: 'create_time',
    fixed: 'right'
  }
]
const orderTableLoading = ref(false)
async function getOrderList() {
  try {
    orderTableLoading.value = true
    const params = {
      filter: orderQueryFilter.value,
      op: orderQueryOp,
      ..._.omit(orderPagination.value, 'total')
    }
    const res: any = await salesApi.queryList(params)
    const list = res.data.data

    if (orderPagination.value.page === 1) {
      let checkOrder = _(checkOrderList.value).filter('is_load').value()
      const localSearchKeys = ['no', 'create_time', 'salesman_id', 'store_id']
      // 处理编辑时的本地订单数据筛选
      for (const key of localSearchKeys) {
        if (!orderQueryFilter.value[key] || orderQueryFilter.value[key].length === 0 || orderQueryFilter.value[key] === '') continue
        checkOrder = _.filter(checkOrder, (item) => {
          if (key === 'no') {
            return item[key].match(new RegExp(orderQueryFilter.value[key], 'i'))
          } else if (key === 'create_time') {
            const [start, end] = orderQueryFilter.value[key]
            const startTime = dayjs(start).format('YYYY-MM-DD 00:00:00')
            const endTime = dayjs(end).format('YYYY-MM-DD 23:59:59')
            return dayjs(item[key]).isBetween(startTime, endTime, null, '[]')
          } else {
            return item[key] === orderQueryFilter.value[key]
          }
        })
      }
      orderList.value = checkOrder.concat(list)
      if (removedOrders.value) {
        // 将去掉的订单添加到未选中的订单列表中
        removedOrders.value.forEach((order) => {
          if (!orderList.value.some((item) => item.id === order.id)) {
            orderList.value.push(order)
          }
        })
      }
      orderSelectedKeys.value = _(checkOrderList.value)
        .map('id')
        .concat(orderSelectedKeys.value)
        .uniq()
        .filter((key) => !orderUnSelectedKeys.has(key))
        .value()
      orderSelectedRows.value = _(checkOrderList.value)
        .concat(orderSelectedRows.value)
        .uniqBy('id')
        .filter((item) => !orderUnSelectedKeys.has(item.id))
        .value()
    } else {
      orderList.value = list
    }
    orderPagination.value.total = res.data.total + checkOrderList.value.length
  } catch (error: any) {
    message.error(error.msg)
  } finally {
    orderTableLoading.value = false
  }
}

function orderTotalComputed(total: number) {
  const is_load_num = 0
  return `已分配${orderSelectedKeys.value.length}条 未分配${is_load_num + total - orderSelectedKeys.value.length}条`
}

// 选择项配置
const orderSelectedKeys = ref<string[]>([])
const orderUnSelectedKeys = new Set()
const orderSelectedRows = ref<any[]>([])
function getOrderSelection() {
  return {
    onChange: (keys, rows) => {
      orderSelectedKeys.value = keys
      orderSelectedRows.value = rows
    },
    onSelect: (record, selected) => {
      const fn = selected ? 'delete' : 'add'
      orderUnSelectedKeys[fn](record.id)
    },
    onSelectAll: (selected, _, changeRows) => {
      const fn = selected ? 'delete' : 'add'
      for (const record of changeRows) {
        orderUnSelectedKeys[fn](record.id)
      }
    },
    selectedRowKeys: orderSelectedKeys.value,
    preserveSelectedRowKeys: true,
    fixed: true
  }
}

// Modal
const showOrderModal = ref(false)
watch(
  () => showOrderModal.value,
  (val) => {
    if (!val) {
      resetOrderQuery()
    }
  }
)
function changeOrderModal(flag: boolean) {
  showOrderModal.value = flag
}

// ---------------------------- 订单联动 ----------------------------
function confirmAddCheckOrder() {
  for (const item of orderSelectedRows.value) {
    if (checkOrderList.value.find((row) => row.id === item.id)) continue
    checkOrderList.value.push(item)
  }

  // 去掉未选中的订单
  const currentRemovedOrders = checkOrderList.value.filter((item) => orderUnSelectedKeys.has(item.id))
  // 将去掉的订单添加到 removedOrders 中
  currentRemovedOrders.forEach((order) => {
    if (!removedOrders.value.some((item) => item.id === order.id)) {
      removedOrders.value.unshift(order) // 使用 unshift 方法将订单添加到最前面
    }
  })

  checkOrderList.value = checkOrderList.value.filter((item) => !orderUnSelectedKeys.has(item.id))
  orderUnSelectedKeys.clear()
  changeOrderModal(false)
}

// ---------------------------- 地图派单 ----------------------------
const { push } = useRouter()
function toMap(url: string) {
  if (form.value.driver_id) {
    onClose()
    push(`/map${url}?id=${form.value?.id}&driver_id=${form.value.driver_id}&escort_driver_id=${form.value.escort_driver_id}`)
  } else {
    message.error('请选择司机')
  }
}

// 表单标题
const formTitle = computed(() => (form.value?.id ? '编辑' : '手动调度'))
</script>
<style scoped lang="less">
:deep(.ant-badge .ant-badge-count) {
  height: 16px;
  line-height: 16px;
  font-size: 10px;
}
</style>
